//
//  ResultLookViewController.m
//  MobileStudy
//
//  Created by cuihongbao on 13-6-30.
//  Copyright (c) 2013年 hongbao.cui. All rights reserved.
//

#import "ResultLookViewController.h"
#import "PaperListView.h"
#import "XingAndLabel_UIView.h"
#import "Sqlite.h"
#import "CaseQuestionView.h"
#import "ApplicationUtils.h"
#import "FMNavgationItem.h"
#import "SwipeView.h"
#import "SynExericisesPaperData.h"
#import "ApplicationUtils.h"
#import "AnswerJsonObject.h"
#import "NSDictionary+RequestEncoding.h"
#import "FMSNetWorkModule.h"
#import "ZipArchive.h"
#import "IndexViewController.h"
@interface ResultLookViewController ()<UIScrollViewDelegate,PaperListViewDelegate,SwipeViewDataSource,SwipeViewDelegate,IndexBtnClickedDelegate>
{
    NSMutableArray *_dataList;
    NSMutableArray *paperArray;
    NSMutableArray *answerArray;
//    NSMutableSet *dataSet;
}
@property (nonatomic,strong)NSMutableArray *dataList;
@property (nonatomic,strong) NSMutableArray *paperArray;
@property (nonatomic,strong) NSMutableArray *listArray;
@property (nonatomic,strong) NSMutableArray *answerArray;//存放多选的答案数组
@property(nonatomic,strong) SwipeView *swipeView;
//@property(nonatomic,strong) NSMutableSet *dataSet;
@end

@implementation ResultLookViewController
@synthesize dataList = _dataList;
@synthesize inforDict;
@synthesize paperArray;
@synthesize viewList;
@synthesize dataQuestionDict;
@synthesize answerArray;
//@synthesize anlysisArray;
@synthesize answerStr;
@synthesize questionStr;
@synthesize isMark;
//@synthesize dataSet;
//上一页按钮
-(IBAction)previousBtnClicked:(id)sender{
    if (currentPage==0) {
        [ApplicationUtils makeToast:@"已第一页" withImageName:@"no" withView:self.view];
        return;
    }
    [_swipeView scrollToPage:currentPage-1 duration:0.5];
}
//收藏按钮
-(IBAction)collectionBtnClicked:(UIButton *)sender{
    NSMutableDictionary *dataDict = (NSMutableDictionary *)[self.paperArray objectAtIndex:currentPage];
    if (!dataDict) {
        return;
    }
    NSString *qstId =[dataDict objectForKey:@"qstId"];
    NSString *paperId = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"paper_id"]];
    NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
    BOOL isCollection = NO;
    if ([favourite_flag isEqualToString:@"1"]) {
        isCollection = YES;
    }
    if (!isCollection) {
        if ([Sqlite updateCollection:@"1" orderId:qstId paperId:paperId]) {
            [ApplicationUtils makeToast:@"收藏成功" withImageName:@"Star" withView:self.view];
            FMSCHBLog(@"收藏成功");
            [dataDict setObject:@"1" forKey:@"favourite_flag"];
        }else{
            [ApplicationUtils makeToast:@"收藏失败!" withImageName:@"Star" withView:self.view];
            FMSCHBLog(@"收藏失败");
        }
    }else{
        if ([Sqlite updateCollection:@"0" orderId:qstId paperId:paperId]) {
            FMSCHBLog(@"取消收藏");
            [ApplicationUtils makeToast:@"取消收藏!" withImageName:@"Star" withView:self.view];
            [dataDict setObject:@"0" forKey:@"favourite_flag"];
        }else{
            [ApplicationUtils makeToast:@"取消收藏失败!" withImageName:@"Star" withView:self.view];
            FMSCHBLog(@"取消收藏失败!");
        }
    }
    [sender setSelected:!isCollection];
}
//下一页按钮
-(IBAction)nextBtnClicked:(id)sender{
    if ([self.paperArray count]-1 == currentPage) {
        [ApplicationUtils makeToast:@"已最后一页" withImageName:@"no" withView:self.view];
        return;
    }
    [_swipeView scrollToPage:currentPage+1 duration:0.5];
}
//-(void)updateMainView:(NSMutableDictionary *)_hudDict{
    //    [self.expansionTableView reloadData];
//    [ApplicationInfo releaseHudDict:hudDict];
//}
//-(void)initNetData:(NSMutableDictionary *)hudDict{
//    @autoreleasepool {
//        NSString *paperId = [NSString stringWithFormat:@"%@",[inforDict objectForKey:@"id"]];
//        NSString *urlString = [NSString stringWithFormat:@"%@/rest/mobilestudy/paper/%@?authToken=%@",DEFAULT_URL,paperId,@"asdfweiryiweuyriu"];
//        
//        //添加到ASINetworkQueue
//        ASINetworkQueue *netWorkQueue  = [[ASINetworkQueue alloc] init];
//        [netWorkQueue reset];
//        [netWorkQueue setShowAccurateProgress:YES];
//        [netWorkQueue go];
//        //初始化Documents路径
//        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//        //初始化临时文件路径
//        NSString *folderPath = [path stringByAppendingPathComponent:@"temp"];
//        //创建文件管理器
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        //判断temp文件夹是否存在
//        BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
//        
//        if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
//            [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
//        }
//        //初始下载路径
//        NSURL *url = [NSURL URLWithString:urlString];
//        //设置下载路径
//        ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
//        [request setTimeOutSeconds:60];
//        //设置ASIHTTPRequest代理
//        request.delegate = self;
//        //初始化保存ZIP文件路径
//        NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"paper_%@.zip",paperId]];
//        //初始化临时文件路径
//        NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"temp/paper_%@.zip.temp",paperId]];
//        //设置文件保存路径
//        [request setDownloadDestinationPath:savePath];
//        //设置临时文件路径
//        [request setTemporaryFileDownloadPath:tempPath];
//        //设置进度条的代理,
//        //        [request setDownloadProgressDelegate:book];
//        //设置是是否支持断点下载
//        [request setAllowResumeForFileDownloads:YES];
//        [netWorkQueue addOperation:request];
//        //收回request
//        [request release];
//        [netWorkQueue release];
//    }
//}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)back{
    if (isMark) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
    }];
    if (self.lookBackBlock) {
        self.lookBackBlock();
    }
}
-(void)IndexBtnClicked:(UIButton *)sender{
    [_swipeView scrollToPage:sender.tag duration:0.2];
}
-(NSMutableArray *)getType:(NSString *)typeStr array:(NSMutableArray *)array{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity:1];
    for (NSDictionary *dataDict in array) {
        NSString *qtype = [dataDict objectForKey:@"myqtype"];
        if ([qtype isEqualToString:typeStr]) {
            [dataArray addObject:dataDict];
        }
    }
    return dataArray;
}
#pragma mark-右侧答题卡按钮
-(void)rightBarBtnClicked:(id)sender{
    IndexViewController *index = [[IndexViewController alloc] initWithNibName:nil bundle:nil];
    NSMutableDictionary *dataQuestionDict_ = [NSMutableDictionary dictionaryWithCapacity:1];
    NSString *paper_id = [self.inforDict objectForKey:@"paperID"];
    NSMutableArray *array = [Sqlite selectTestQuestion:paper_id];
    NSMutableArray *dataArray1 = [self getType:@"0" array:array];//单选
    NSMutableArray *dataArray2 = [self getType:@"1" array:array];//多选
    NSMutableArray *dataArray3 = [self getType:@"2" array:array];//判断
    NSMutableArray *dataArray4 = [self getType:@"3" array:array];//填空
    NSMutableArray *dataArray5 = [self getType:@"4" array:array];//简答
    NSMutableArray *dataArray6 = [self getType:@"5" array:array];//简答
    NSMutableArray *dataArray7 = [self getType:@"6" array:array];//简答
    NSMutableArray *dataArray8 = [self getType:@"7" array:array];//简答
    NSMutableArray *dataArray9 = [self getType:@"8" array:array];//简答
    NSMutableArray *dataArray10 = [self getType:@"9" array:array];//简答
    
    
    NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:1];
    [dataArray1 count]>0?[list addObject:dataArray1]:NSLog(@"没有单选题");
    [dataArray2 count]>0?[list addObject:dataArray2]:NSLog(@"没有多选题");
    [dataArray3 count]>0?[list addObject:dataArray3]:NSLog(@"没有判断题");
    [dataArray4 count]>0?[list addObject:dataArray4]:NSLog(@"没有填空");
    [dataArray5 count]>0?[list addObject:dataArray5]:NSLog(@"没有主观题");
    [dataArray6 count]>0?[list addObject:dataArray6]:NSLog(@"没有支持题型");
    [dataArray7 count]>0?[list addObject:dataArray7]:NSLog(@"没有支持题型");
    [dataArray7 count]>0?[list addObject:dataArray7]:NSLog(@"没有支持题型");
    [dataArray8 count]>0?[list addObject:dataArray8]:NSLog(@"没有支持题型");
    [dataArray9 count]>0?[list addObject:dataArray9]:NSLog(@"没有支持题型");
    [dataArray10 count]>0?[list addObject:dataArray10]:NSLog(@"没有支持题型");
    
    [dataQuestionDict_ setObject:list forKey:@"questions"];
    index.dataDict = dataQuestionDict_;
    index.delegate = self;
    [self.navigationController pushViewController:index animated:YES];
}
-(void)initRightItemView{
    UIButton *itemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [itemBtn setFrame:CGRectMake(0, 0, 20, 17)];
    [itemBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_btn_class@2x"] forState:UIControlStateNormal];
    [itemBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_btn_class0@2x"] forState:UIControlStateHighlighted];
    [itemBtn addTarget:self action:@selector(rightBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:itemBtn];
    self.navigationItem.rightBarButtonItem = item;
}
-(void)initNavigationBar{
    self.navigationItem.title = @"试题浏览";
    [self initRightItemView];
    FMSCHBLog(@"---viewControllers-----%@",self.navigationController.viewControllers);
//    self.view.backgroundColor = [UIColor colorWithRed:(float)0xF5/0xFF green:(float)0xF4/0xFF blue:(float)0xD4/0xFF alpha:1.0f];
    self.view.backgroundColor = [UIColor whiteColor];
    FMNavgationItem* leftItem = [[FMNavgationItem alloc] init];
    [leftItem.backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems = [leftItem getNavgationItemWithType:WRNavgationTypeLeft Ima:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] ImaHighlight:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] title:@""];
    UIImageView *footerView = (UIImageView *)[self.view viewWithTag:100];
    if (EDUCATION) {
        //收藏
        UIButton *favButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [favButton setImage:[ApplicationUtils getLocalImage:@"st_Options_Collection1@2x"] forState:UIControlStateNormal];
        [favButton setImage:[ApplicationUtils getLocalImage:@"st_Options_Collection@2x"] forState:UIControlStateHighlighted];
        [favButton setImage:[ApplicationUtils getLocalImage:@"st_Options_Collection@2x"] forState:UIControlStateSelected];
        [favButton setTitle:@"收藏" forState:UIControlStateNormal];
        [favButton setTitle:@"收藏" forState:UIControlStateHighlighted];
        [favButton setTitle:@"取消收藏" forState:UIControlStateSelected];
        [favButton setTitleColor:[ApplicationUtils stringTOColor:@"#1cb6a7"] forState:UIControlStateHighlighted];
        [favButton setTitleColor:[ApplicationUtils stringTOColor:@"#1cb6a7"] forState:UIControlStateSelected];
        [[favButton titleLabel] setFont:[UIFont systemFontOfSize:14.0]];
        collectionBtn= favButton;
        [favButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [favButton setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 30)];
        [favButton setFrame:CGRectMake(FMSCREENWIDTH/2-50, 7.5, 100, 30)];
        [favButton addTarget:self action:@selector(collectionBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:favButton];
    }else{
        //上一页
        UIButton *upBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [upBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_previous_pressed.png"] forState:UIControlStateNormal];
        [upBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_previous.png"] forState:UIControlStateHighlighted];
        [upBtn setFrame:CGRectMake(50, 10, 28, 27)];
        [upBtn addTarget:self action:@selector(upPageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:upBtn];
        
        //下一页
        UIButton *downBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [downBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_next_pressed.png"] forState:UIControlStateNormal];
        [downBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_next.png"] forState:UIControlStateHighlighted];
        [downBtn setFrame:CGRectMake(FMSCREENWIDTH-50-28, 10, 28, 27)];
        [downBtn addTarget:self action:@selector(downPageBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:downBtn];
    }
}
-(void)upPageBtnClicked:(id)sender{
    [_swipeView scrollToPage:currentPage-1 duration:0.5];
}
-(void)downPageBtnClicked:(id)sender{
    [_swipeView scrollToPage:currentPage+1 duration:0.5];
}
- (void)viewDidLoad
{
//    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
//    if (systemVersion >= 7.0)
//    {
//        //某个仅支持7.0以上版本的方法
//        self.edgesForExtendedLayout = UIRectEdgeNone;
//        
//    }
//    [super viewDidLoad];
    [self initNavigationBar];
    
    int h = [UIScreen mainScreen].bounds.size.height-22-58-44-titleLabel.frame.size.height;
    if (!_swipeView) {
        _swipeView = [[SwipeView alloc] initWithFrame:CGRectMake(0, 35, FMSCREENWIDTH, h)];
    }
    _swipeView.alignment = SwipeViewAlignmentCenter;
    _swipeView.delegate = self;
    _swipeView.dataSource = self;
    _swipeView.pagingEnabled = YES;
    _swipeView.wrapEnabled = NO;
    _swipeView.itemsPerPage = 1;
    _swipeView.truncateFinalPage = YES;
    [_swipeView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_swipeView];
    
    FMSCHBLog(@"cui--------->:%@",inforDict);
    self.navigationItem.title = @"试卷浏览";
    [ApplicationUtils promptRotateWithViewTitle:@"请稍候..." showView:self.view];
    [NSThread detachNewThreadSelector:@selector(resultData) toTarget:self withObject:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if (IS_STUDY) {
//        
//    }else{
//        self.navigationController.navigationBarHidden = NO;
//    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    if (IS_STUDY) {
//        
//    }else{
//        self.navigationController.navigationBarHidden = YES;
//    }
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    FMSCHBLog(@"self.navigationController.viewControllers:%@",self.navigationController.viewControllers);
}
//-(void)initJsonAnswer{
//    NSString *answerPath = [NSString stringWithFormat:@"%@/answer.json",FMPAPERSAVE_PATH];
//    NSData *fileData = [NSData dataWithContentsOfFile:answerPath];
//    NSString *fileSring = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
//    NSLog(@"fileSring:%@",fileSring);
//    NSError *error = nil;
//    NSMutableSet *set = (NSMutableSet *)[NSJSONSerialization JSONObjectWithData:fileData options:kNilOptions error:&error];
//    if (!dataSet) {
//        dataSet = [[NSMutableSet alloc] initWithCapacity:1.0];
//    }
//    for (NSDictionary *dict in set) {
//        AnswerJsonObject *object = [[AnswerJsonObject alloc] init];
//        if (![dict isKindOfClass:[NSDictionary class]]) {
//            break;
//        }
//        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
//        object.parentId =[numberFormatter stringFromNumber:[dict objectForKey:@"parentId"]];
//        object.qstId = [numberFormatter stringFromNumber:[dict objectForKey:@"qstId"]];
//        object.resultFlag = [numberFormatter stringFromNumber:[dict objectForKey:@"resultFlag"]];
//        object.standardAnswer = [dict customValueForKey:@"standardAnswer"];
//        object.subCount = [numberFormatter stringFromNumber:[dict objectForKey:@"subCount"]];
//        object.tqId =  [numberFormatter stringFromNumber:[dict objectForKey:@"tqId"]];
//        object.userAnswer = [dict customValueForKey:@"userAnswer"];
//        object.userScoreRate = [dict customValueForKey:@"userScoreRate"];
//        object.viewTypeId = [numberFormatter stringFromNumber:[dict objectForKey:@"viewTypeId"]];
//        [dataSet addObject:object];
//    }
//    
//    FMSCHBLog(@"dataSet------------>%@",dataSet);
//    for (NSInteger j=0; j<[self.paperArray count]; j++) {
//        NSMutableDictionary *dict = [self.paperArray objectAtIndex:j];
//        NSString  *qstId = [dict customValueForKey:@"qstId"];
//        FMSCHBLog(@"qstId---->:%@",qstId);
//        for (AnswerJsonObject *object in dataSet) {
//            FMSCHBLog(@"object.qstId---->:%@",object.qstId);
//            if ([qstId isEqualToString:object.qstId]) {
//                [dict setObject:object.userAnswer forKey:@"user_answer"];
//            }
//        }
//    }
//    
//}
-(void)initAnswerData{
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.inforDict objectForKey:@"paperID"]];
    NSString *authToken = [NSString stringWithFormat:@"%@",[self.inforDict objectForKey:@"authToken"]];
    NSString  *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *ip_host = [dataDict objectForKey:@"ip_host"];
    NSString *ip_root = [dataDict objectForKey:@"ip_root"];
    NSString *urlString = [NSString stringWithFormat:@"http://%@%@getUserExamResult.do?homeworkid=%@&authToken=%@",ip_host,ip_root,paperId,authToken];
    //初始化Documents路径
    NSString *path = [NSString stringWithFormat:@"%@/%@",FMPAPERSAVE_PATH,paperId];//[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Paper"];
    FMSCHBLog(@"FMPAPERSAVE_PATH:%@",FMPAPERSAVE_PATH);
    if ([ApplicationUtils isFileExitsAtPath:path]) {
        FMSCHBLog(@"创建目录成功");
    }
    //初始化保存ZIP文件路径
    if ([Sqlite deleteTestQuestionIdAt:paperId]) {//清除试题成功，之后再保存
        FMSCHBLog(@"试题清除成功");
    }else{
        FMSCHBLog(@"试题清除失败!");
    }
    NSString *filePath = [path stringByAppendingPathComponent:@"answer.zip"];
//    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
    [[FMSNetWorkModule sharedInstance] downloadFatAssFileFrom:urlString toFile:filePath completionCB:^(id result) {
        if (result == nil) {
            //初始化ZipArchive
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                                     0), ^{
                //删除本地的json文件和image下的图片
//                NSString *pathStrJ = [NSString stringWithFormat:@"%@/answer.json",path];
//                [ApplicationUtils deleteExitsFile:pathStrJ];
//                pathStrJ =[NSString stringWithFormat:@"%@/image",path];
//                [ApplicationUtils deleteExitsFile:pathStrJ];
                
                ZipArchive *zip = [[ZipArchive alloc] init];
                BOOL success = NO;
                if ([zip UnzipOpenFile:filePath]) {
                    success = [zip UnzipFileTo:path overWrite:YES];//解压文件
                    [zip UnzipCloseFile];//关闭
                    if (success) {
                        //解压成功
                        FMSCHBLog(@"unzip success.............");
                        //                        NSString *status = [self.urlDict objectForKey:@"status"];
                        //                        if ([status isEqualToString:@"1"]) {
                        @try {
                            //同步试卷数据中zip包的数据到数据库
                            NSString *pathStr = [NSString stringWithFormat:@"%@/answer.json",path];
                            NSString *jsonStr = [[NSString alloc]initWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:nil];
                            NSArray *dataArray = [ApplicationUtils objectFromJson:jsonStr];
                            for (NSDictionary *answerDict in dataArray) {
                                NSString *qstId = [answerDict objectForKey:@"qstId"];
                                NSString *user_answer = [answerDict objectForKey:@"userAnswer"];
                                NSString *author_id = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
                                NSString *userAnswerImage = [answerDict objectForKey:@"userAnswerImage"];
                                NSString *updateSQL = [NSString stringWithFormat:@"update testQuestionTable set user_answer = '%@',userAnswerImage='%@' where  paper_id='%@' and author_id ='%@' and qstId = '%@' ;", user_answer,userAnswerImage,paperId,author_id,qstId];
                                BOOL success =[Sqlite updateUserAnswer:updateSQL];
                                if (success) {
                                    FMSCHBLog(@"---更新答案成功---");
                                }
                            }
                        }
                        @catch (NSException *exception) {
                            dispatch_async(dispatch_get_main_queue(), ^{
//                                [ApplicationUtils showAlertMSG:[exception description]];
                                FMSCHBLog(@"exception---------%@",[exception description]);
                            });
                        }
                        @finally {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [self performSelectorOnMainThread:@selector(updateZipMainView) withObject:nil waitUntilDone:NO];
                                currentPage = 0;
                            });
                            return;
                        }
                        //                        }
                        //删除answer.zip文件
                        BOOL success1 = [ApplicationUtils deleteExitsFile:filePath];
                        if (success1) {
                            NSLog(@"删除zip文件成功");
                        }
                    }else {
                        FMSCHBLog(@"zip UnzipFileTo fail................");
                    }
                }else{
                    FMSCHBLog(@"open fail................");
                }
            });
        }else{
            [ApplicationUtils promptRemove];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷同步加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert setTag:4];
            [alert show];
            [self performSelectorOnMainThread:@selector(updateZipMainView) withObject:nil waitUntilDone:NO];
            currentPage = 0;
        }
    }];
}
-(void)initNetData{
    NSString *urlString = [self.inforDict objectForKey:@"paperFileURL"];
    //    NSString *urlString = @"http://study.yuetong.cn:8080/drappub/rest/mobilestudy/paper/8056?authToken=feixiang0";
    //初始化Documents路径
    NSString *path = FMPAPERSAVE_PATH;//[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Paper"];
    FMSCHBLog(@"FMPAPERSAVE_PATH:%@",FMPAPERSAVE_PATH);
    if ([ApplicationUtils isFileExitsAtPath:path]) {
        FMSCHBLog(@"创建目录成功");
    }
    //初始化保存ZIP文件路径
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.inforDict objectForKey:@"paperID"]];
    if ([Sqlite deleteTestQuestionIdAt:paperId]) {//清除试题成功，之后再保存
        FMSCHBLog(@"试题清除成功");
    }else{
        FMSCHBLog(@"试题清除失败!");
    }
    NSString *paperStr = [NSString stringWithFormat:@"paper_%@.zip",paperId];
    NSString *filePath = [path stringByAppendingPathComponent:paperStr];
//    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
    [[FMSNetWorkModule sharedInstance] downloadFatAssFileFrom:urlString toFile:filePath completionCB:^(id result) {
        if (result == nil) {
            //初始化ZipArchive
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                                     0), ^{
                ZipArchive *zip = [[ZipArchive alloc] init];
                BOOL success = NO;
                if ([zip UnzipOpenFile:filePath]) {
                    success = [zip UnzipFileTo:path overWrite:YES];//解压文件
                    [zip UnzipCloseFile];//关闭
                    if (!success) {
                        //解压失败
                    }else {
                        //解压成功
                        FMSCHBLog(@"unzip success.............");
                        NSError *error = nil;
                        NSString *pathStr = [NSString stringWithFormat:@"%@/paper.XML",path];
                        NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];
                        //    NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"Paper" ofType:@"xml"];
                        //     NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];//test
                        if (!error) {
                            SynExericisesPaperData *paperData = [[SynExericisesPaperData alloc] init];
                            NSMutableDictionary *paperDict = [paperData PaperData:paperXmlString];
                            FMSCHBLog(@"paperDict:%@",paperDict);
                            NSString *paper_title = [paperDict objectForKey:@"paper_title"];
                            NSString *paper_score = [paperDict objectForKey:@"paper_score"];
                            NSString *paper_time = [paperDict objectForKey:@"paper_time"];
                            NSMutableArray *array = [paperDict objectForKey:@"questions"];
                            NSMutableArray *questions = [NSMutableArray arrayWithCapacity:1];
                            //                NSMutableArray *array_ = [Sqlite selectTestQuestion:paperId];
                            if (!self.paperArray) {
                                self.paperArray = [NSMutableArray array];
                            }
                            NSInteger number = 0;
                            for (int i=0; i<[array count]; i++) {
                                NSMutableArray *questionArray = [[array objectAtIndex:i] objectForKey:@"question"];
                                NSString *qtype_name =  [[array objectAtIndex:i] objectForKey:@"type_name"];
                                NSNumber *myqtypeNumber = [[array objectAtIndex:i] objectForKey:@"myqtype"];
                                NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                                NSString *myqtype = [numberFormatter stringFromNumber:myqtypeNumber];
                                [self.paperArray removeAllObjects];
                                [self.paperArray addObjectsFromArray:questionArray];
                                NSMutableString *answerStr_ = [[NSMutableString alloc] initWithCapacity:1];
                                for (int j=0; j<[self.paperArray count]; j++) {
                                    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:j];
                                    NSString *qtype = [dataDict objectForKey:@"qtype"];
                                    [dataDict setObject:myqtype forKey:@"myqtype"];
                                    if ([qtype isEqualToString:@"1"]||[qtype isEqualToString:@"2"]) {
                                        [questions addObjectsFromArray:questionArray];
                                        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",nil];
                                        [dataDict addEntriesFromDictionary:dict];
                                        
                                        NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                        FMSCHBLog(@"cui---hong-------has_sub-----------%@",has_sub);
                                        if (has_sub) {
                                            [dataDict setObject:has_sub forKey:@"has_sub"];
                                        }
                                        [dataDict setObject:paper_title forKey:@"paper_title"];
                                        [dataDict setObject:paper_score forKey:@"paper_score"];
                                        [dataDict setObject:paper_time forKey:@"paper_time"];
                                        [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                        [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                        BOOL success = [Sqlite insertTestQuestion:dataDict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        number++;
                                    }else if([qtype isEqualToString:@"3"]){
                                        //判断题
                                        [questions addObjectsFromArray:questionArray];
                                        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",nil];
                                        [dataDict addEntriesFromDictionary:dict];
                                        
                                        NSArray  *array = [NSArray arrayWithObjects:@"正确",@"错误",nil];
                                        NSMutableDictionary *optionsDict = [NSMutableDictionary dictionaryWithCapacity:1];
                                        //                                        NSArray *seArray = [NSArray arrayWithObjects:@"option_a",@"option_b", nil];
                                        //                                        for (int i=0; i<[array count]; i++) {
                                        //                                            NSString *str = [array objectAtIndex:i];
                                        [optionsDict setObject:array forKey:@"options"];
                                        //                                        }
                                        NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                        FMSCHBLog(@"cui---hong-------has_sub-----------%@",has_sub);
                                        if (has_sub) {
                                            [dataDict setObject:has_sub forKey:@"has_sub"];
                                        }
                                        [dataDict addEntriesFromDictionary:optionsDict];
                                        [dataDict setObject:paper_title forKey:@"paper_title"];
                                        [dataDict setObject:paper_score forKey:@"paper_score"];
                                        [dataDict setObject:paper_time forKey:@"paper_time"];
                                        [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                        [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                        BOOL success = [Sqlite insertTestQuestion:dataDict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        number++;
                                    }else{//简答题,案例分析题
                                        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:1];
                                        [answerStr_ appendFormat:@"<p>%@</p>",[dataDict objectForKey:@"answer"]];
                                        [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:answerStr_ forKey:@"answer"]];
                                        [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:[dataDict objectForKey:@"questionContent"] forKey:@"content"]];
                                        [dict setObject:paperId forKey:@"paper_id"];
                                        [dict addEntriesFromDictionary:dataDict];
                                        [dict setObject:@"0" forKey:@"favourite_flag"];
                                        [dict setObject:paper_title forKey:@"paper_title"];
                                        [dict setObject:paper_score forKey:@"paper_score"];
                                        [dict setObject:paper_time forKey:@"paper_time"];
                                        [dict setObject:qtype_name forKey:@"qtype_name"];
                                        [dict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                        BOOL success = [Sqlite insertTestQuestion:dict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        [dict removeAllObjects];
                                        number++;
                                    }
                                }
                                
                            }
                            if (IS_STUDY) {//作业管理同步答案
                                [self initAnswerData];//我选择的答案
                            }
                        }
                    }
                }else{
                    FMSCHBLog(@"open fail................");
                }
            });
        }else{
            [ApplicationUtils promptRemove];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert setTag:4];
            [alert show];
        }
    }];
}
-(void)resultData{
    @autoreleasepool {
        if (IS_STUDY) {//作业管理
            NSString *paperId = [NSString stringWithFormat:@"%@",[inforDict objectForKey:@"paperID"]];
            NSString *exam_time = [NSString stringWithFormat:@"%@",[inforDict objectForKey:@"exam_time"]];
            if (!self.paperArray) {
                self.paperArray = [NSMutableArray array];
            }
            [self.paperArray removeAllObjects];
            NSMutableArray *array = [Sqlite selectTestQuestion:paperId];
            if ([array count]>0) {
                [self initAnswerData];
//                [self.paperArray addObjectsFromArray:array];//存为全局，以后使用
            }else{
                [self initNetData];
            }
            
        }else{//移动学习
            NSString *paperId = [NSString stringWithFormat:@"%@",[inforDict objectForKey:@"paperID"]];
            NSString *exam_time = [NSString stringWithFormat:@"%@",[inforDict objectForKey:@"exam_time"]];
            if (!self.paperArray) {
                self.paperArray = [NSMutableArray array];
            }
//            [self.paperArray removeAllObjects];
//            NSMutableArray *array = [Sqlite selectAllQuestion:paperId exam_time:exam_time];
//            [self.paperArray addObjectsFromArray:array];//存为全局，以后使用
//            NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共01/%lu题",[inforDict objectForKey:@"name"],(unsigned long)[self.paperArray count]];
//            [titleLabel setText:paperTitleAndCount];
//            [titleLabel setTextColor:[UIColor whiteColor]];
            [self performSelectorOnMainThread:@selector(updateZipMainView) withObject:nil waitUntilDone:NO];
            currentPage = 0;
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    if (_dataList) {
        _dataList = nil;
    }
    if (self.inforDict) {
        self.inforDict = nil;
    }
    if (titleLabel) {
        titleLabel =nil;
    }
    if (self.paperArray) {
        self.paperArray = nil;
    }
    if (self.viewList) {
        self.viewList = nil;
    }
    if (self.dataQuestionDict) {
        self.dataQuestionDict = nil;
    }
    if (collectionBtn) {
        collectionBtn = nil;
    }
    if (answerArray) {
        answerArray = nil;
    }
//    if (self.anlysisArray) {
//        self.anlysisArray = nil;
//    }
    if (self.answerStr) {
        self.answerStr = nil;
    }
    if (self.questionStr) {
        self.questionStr = nil;
    }
    if (_swipeView) {
        for (UIView *subView in [_swipeView subviews]) {
            [subView removeFromSuperview];
        }
        self.swipeView = nil;
    }
}
//PaperListViewDelegate
/*
-(void)selectBtnClicked:(UIButton *)sender{
    
    //    NSArray  *array = [self.dataQuestionDict objectForKey:@"questions"];//
    //    NSMutableArray *singlequestionArray = [[array objectAtIndex:0] objectForKey:@"question"];//单选数组
    //
    noSelected = 0;
    NSDictionary *dataDict = [self.paperArray objectAtIndex:currentPage];
    NSString *answer = [dataDict objectForKey:@"answer"];
    NSRange range;
    if (answer.length>3) {
        range.location =3;
        range.length =1;
    }else{
        range.location =0;
        range.length =answer.length;
    }
    answer = [answer substringWithRange:range];
    NSString *orderIdStr =[dataDict objectForKey:@"orderid"];
    NSString *titleStr =[dataDict objectForKey:@"questionContent"];
    NSString *qtype = [dataDict objectForKey:@"qtype"];
    NSString *str = [NSString stringWithFormat:@"%@.%@",orderIdStr,titleStr];
    CGSize size_0 = CGSizeMake(300, 1000);
    CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:16.0]constrainedToSize:size_0 lineBreakMode:UILineBreakModeCharacterWrap];
    int h = size.height+30;
    NSArray  *optionsArray = [dataDict objectForKey:@"options"];
    XingAndLabel_UIView  *titleLableView = (XingAndLabel_UIView *)sender.superview;
    NSString *optionsStr =titleLableView.titleLabel.text;
    NSString *selectionStr = [[optionsStr componentsSeparatedByString:@"."] objectAtIndex:0];
    if (!self.answerArray) {
        self.answerArray = [NSMutableArray arrayWithCapacity:1];
    }
    if ([qtype isEqualToString:@"1"]) {
        [self.answerArray removeAllObjects];
        [self.answerArray addObject:selectionStr];
        FMSCHBLog(@"optionsStr:%@",optionsStr);
        NSString *imageStr = nil;
        if (answer==nil) {
            answer = @"您没有选择答案";
            imageStr = @"table_yes.png";
        }else{
            if ([selectionStr isEqualToString:answer]) {
                imageStr = @"table_no.png";
            }else{
                imageStr = @"table_yes.png";
            }
        }
        NSString *anyliseHTMLData = [NSString stringWithFormat:@"<p><a><font color=\"#0000FF\">您的答案:</font>%@     </a><img src=\"%@\" width=\"18\"></p><p><a><font color=\"#0000FF\">知识点:</font>%@</a></p><p><a><font color=\"#0000FF\">正确答案:</font>%@</a></p><a><font color=\"#0000FF\">试题分析:</font> %@</a>",selectionStr,imageStr,[dataDict objectForKey:@"category_name"],answer,[dataDict objectForKey:@"analysis"]];
        CGSize anyliseSize = [anyliseHTMLData sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:CGSizeMake(300, 1000)];
        UILabel *lineLabel = (UILabel *)[titleLableView.superview viewWithTag:1000];
        [lineLabel setHidden:NO];
        
        UIWebView *webView = (UIWebView *)[titleLableView.superview viewWithTag:1001];
        [webView setHidden:NO];
        [webView loadHTMLString:anyliseHTMLData baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
        [(UIScrollView *)titleLableView.superview setContentSize:CGSizeMake(300,h+([optionsArray count]+1)*43+anyliseSize.height+1+40)];
        
    }else{
        if (![self.answerArray containsObject:selectionStr]) {
            [self.answerArray addObject:selectionStr];
        }else{
            [self.answerArray removeObject:selectionStr];
        }
        
    }
}*/
//-(void)zipArchive{
//    //初始化Documents路径
//	NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//	//初始化保存ZIP文件路径
//    NSString *paperId = [NSString stringWithFormat:@"%@",[inforDict objectForKey:@"id"]];
//    NSString *paperStr = [NSString stringWithFormat:@"paper_%@.zip",paperId];
//	NSString *filePath = [path stringByAppendingPathComponent:paperStr];
//	//初始化ZipArchive
//	ZipArchive *zip = [[ZipArchive alloc] init];
//	BOOL result = NO;
//	if ([zip UnzipOpenFile:filePath]) {
//		result = [zip UnzipFileTo:path overWrite:YES];//解压文件
//		[zip UnzipCloseFile];//关闭
//	}else{
//        FMSCHBLog(@"open fail................");
//    }
//    //	[MBProgressHUD hideHUDForView:self.view animated:YES];
//	if (!result) {
//		//解压失败
//		FMSCHBLog(@"unzip fail................");
//	}else {
//		//解压成功
//		FMSCHBLog(@"unzip success.............");
//        NSError *error = nil;
//        NSString *pathStr = [NSString stringWithFormat:@"%@/paper.XML",path];
//        NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];
//        if (!error) {
//            SynExericisesPaperData *paperData = [[[SynExericisesPaperData alloc] init] autorelease];
//            NSMutableDictionary *paperDict = [paperData initPaperData:paperXmlString];
//            FMSCHBLog(@"paperDict:%@",paperDict);
//            if (!self.dataQuestionDict) {
//                self.dataQuestionDict = [NSMutableDictionary dictionaryWithDictionary:paperDict];
//            }
////            [paperData release];
//            NSMutableArray *array = [paperDict objectForKey:@"questions"];
//            NSMutableArray *questions = [NSMutableArray arrayWithCapacity:1];
//            for (int i=0; i<[array count]; i++) {
//                if (i<2) {
//                    NSMutableArray *questionArray = [[array objectAtIndex:i] objectForKey:@"question"];
//                    [questions addObjectsFromArray:questionArray];
//                    allCount = [questions count];   //保存选择题和多选题的个数
//                }else{
//                    NSArray *anlysis = [[array objectAtIndex:i] objectForKey:@"question"];
//                    [self.anlysisArray addObjectsFromArray:anlysis];
//                    [questions addObjectsFromArray:self.anlysisArray];//保存案例题的
//                }
//            }
//            if (!self.paperArray) {
//                self.paperArray = [NSMutableArray array]; 
//            }
//            [self.paperArray removeAllObjects];
////            NSArray *array = [Sqlite selectTestQuestion:paperId];
//            [self.paperArray addObjectsFromArray:questions];//存为全局，以后使用
//            NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%d题",[inforDict objectForKey:@"name"],[self.paperArray count]];
//            [titleLabel setText:paperTitleAndCount];
//            [self performSelectorOnMainThread:@selector(updateZipMainView) withObject:nil waitUntilDone:NO];
//        }else{
//            
//        }
//        
//    }
//    [zip release];
//    
////    if (!self.paperArray) {
////        self.paperArray = [NSMutableArray array];
////    }
////    [self.paperArray removeAllObjects];
////    NSArray *array = [Sqlite selectTestQuestion:paperId];
////    [self.paperArray addObjectsFromArray:array];//存为全局，以后使用
////    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%d题",[inforDict objectForKey:@"paper_title"],[self.paperArray count]];
////    [titleLabel setText:paperTitleAndCount];
////    [self performSelectorOnMainThread:@selector(updateZipMainView) withObject:nil waitUntilDone:NO];
//    
//}
//-(void)setDataQuestionView:(UIScrollView *)scrollView{
//    if (currentPage<allCount) {
//        NSArray *resultArray = [inforDict objectForKey:@"resultArray"];
//        NSString *user_answer = [resultArray objectAtIndex:currentPage]; //user_answer
//            PaperListView *pList = (PaperListView *)[scrollView viewWithTag:2000+currentPage];
//            if (pList) {
//                return;
//            }
//            NSArray *opArray = [NSArray arrayWithObjects:@"option_a",@"option_b",@"option_c",@"option_d",@"option_e",@"option_f",nil];
//                NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:currentPage];
//            [dataDict addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:[dataDict objectForKey:@"content"], @"questionContent",nil]];
//                if (user_answer) {
//                    [dataDict setObject:user_answer forKey:@"user_answer"];
//                }
//                NSMutableArray *eArray = [NSMutableArray arrayWithCapacity:1];
//                for (int i=0; i<[opArray count]; i++) {
//                    NSString *option = [dataDict objectForKey:[opArray objectAtIndex:i]];
//                    if (![option isEqualToString:@"(null)"]) {
//                        [eArray addObject:option];
//                    }
//                }
//                [dataDict setObject:eArray forKey:@"options"];
//                [PaperListView setDataDict:dataDict];
//                NSString *qtype = [dataDict objectForKey:@"qtype"];
//                BOOL isSingle;
//                if ([qtype isEqualToString:@"1"]) {
//                    isSingle = YES;
//                }else{
//                    isSingle = NO;
//                }
//                PaperListView  *listView = [[PaperListView alloc] initWithFrame:CGRectMake(FMSCREENWIDTH*currentPage, 0, FMSCREENWIDTH, scrollView.frame.size.height)isSingle:isSingle isShowAnswer:YES anlysise:NO dataDict:dataDict];
//                [listView setPaperDelegate:self];
//                listView.paperDict = [self.paperArray objectAtIndex:0];
//                [listView setTag:2000+currentPage];
//                [listView setBackgroundColor:[UIColor clearColor]];
//                [scrollView addSubview:listView];
//    }else{
//        //由于案例题de数据没有分层，根据has_sub判断显示方式
//        CaseQuestionView *plist = (CaseQuestionView *)[scrollView viewWithTag:300+currentPage];
//        if (plist) {
//            return;
//        }
//        NSMutableDictionary *anlysisDict =[self.paperArray objectAtIndex:currentPage];
//            CaseQuestionView  *caseView = [[CaseQuestionView alloc] initWithFrame:CGRectMake(FMSCREENWIDTH*currentPage, 0, FMSCREENWIDTH, scrollView.frame.size.height) isSingle:NO isShowAnswer:YES anlysise:NO dataDict:anlysisDict];
//            [caseView setBackgroundColor:[UIColor clearColor]];
//            [caseView setCqdelegate:self];
//            caseView.isShowAnswer_ = YES;
////            [caseView showAnswer];
//            [caseView setTag:300+currentPage];
//            [scrollView addSubview:caseView];
//    }
//}
-(void)updateZipMainView{
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.inforDict objectForKey:@"paperID"]];
    NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
    [self.paperArray removeAllObjects];
    [self.paperArray addObjectsFromArray:array_afterSave];
    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:currentPage];
    NSString *paper_title_ = [dataDict objectForKey:@"paper_title"];
//    NSString *qtype = [dataDict objectForKey:@"qtype"];
//    if ([qtype isEqualToString:@"1"]) {
//        qtype = @"(单)";
//    }else if([qtype isEqualToString:@"2"]){
//        qtype = @"(多)";
//    }else if([qtype isEqualToString:@"3"]){
//        qtype = @"(判)";
//    }else if([qtype isEqualToString:@"4"]){
//        qtype = @"(简)";
//    }else{
//        qtype = @"(其他)";
//    }
//    NSString *paper_title = nil;
    if ([self.paperArray count]>0) {
        NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共01/%02lu题",[inforDict objectForKey:@"name"],(unsigned long)[self.paperArray count]];
        [titleLabel setText:paperTitleAndCount];
        [titleLabel setTextColor:[UIColor whiteColor]];
        
        if ([self.paperArray count]==0) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        [_swipeView reloadData];
        [ApplicationUtils promptRemove];
    }else{
        [ApplicationUtils promptRemove];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert setTag:4];
        [alert show];
        return ;
    }
    //    NSMutableArray *singlequestionArray = [[array objectAtIndex:0] objectForKey:@"question"];
    
    //    }
//    [self setDataQuestionView:scrollView];
//    int count=0;
//    for (int i=allCount; i<[self.paperArray count]; i++) {
//        NSDictionary *dict = [self.paperArray objectAtIndex:i];
//        NSString *str = [dict objectForKey:@"has_sub"];
//        if ([str isEqualToString:@"1"]) {
//            count++;
//        }
//    }
//    total =allCount+count;
//    [scrollView setContentSize:CGSizeMake(FMSCREENWIDTH*total, scrollView.frame.size.height)];
//    [scrollView setDelegate:self];
//    [scrollView setPagingEnabled:YES];
//    [scrollView setTag:99];
//    [self.view addSubview:scrollView];

    //更新收藏按钮
//    NSDictionary *dataDict = [self.paperArray objectAtIndex:currentPage];
    if (!dataDict) {
        return;
    }
    NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
    BOOL isCollection = NO;
    if ([favourite_flag isEqualToString:@"1"]) {
        isCollection = YES;
    }
    [collectionBtn setSelected:isCollection];
    
    //更新答案
    BOOL  success = [Sqlite updateUserAnswer:@"" paperId:paperId];
    if (success) {
        FMSCHBLog(@"清楚答案成功!");
    }else{
        FMSCHBLog(@"清楚答案失败!");
    }
}
#pragma -
#pragma UIWebViewDelegate
//由于加载图片加载相对文字加载缓慢本该 webViewDidFinishLoad先加载完，-(void)webViewDidFinishLoading:(id)_self Y:(CGFloat)_y随后加载完，而有图片的，正好相反因此的重设UI

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//            [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '250%'"];
    UIScrollView *scrollView = (UIScrollView *)[self.view viewWithTag:99];
    PaperListView *paperList = (PaperListView *)[scrollView viewWithTag:2000+currentNextPage];
    [paperList setContentSize:CGSizeMake(FMSCREENWIDTH-20,webView.frame.origin.y+webView.scrollView.contentSize.height)];
//    if (webView.tag == 4999) {
//        CGSize  frameSize = webView.scrollView.contentSize;
//        [webView setBackgroundColor:[UIColor clearColor]];
//        [webView setFrame:CGRectMake(webView.frame.origin.x, startWebView, plist.frame.size.width, frameSize.height)];
//        UILabel *lineLabel = (UILabel *)[plist viewWithTag:15000];
//        [lineLabel setFrame:CGRectMake(10, startWebView+5+webView.frame.size.height, lineLabel.frame.size.width, lineLabel.frame.size.height)];
//    }else if (webView.tag == 5000){
//        [self performSelector:@selector(afterUpdateLayOut:) withObject:webView afterDelay:0.2];//延迟0.2秒更新UI避免出现布局不正确情况
//    }
}
#pragma mark  SwipeViewDelegate
#pragma -
- (NSInteger)numberOfItemsInSwipeView:(SwipeView *)swipeView
{
    return [self.paperArray count];
}
//- (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
//{
//    currentPage = index;
//    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:index];
//    PaperListView *listView = (PaperListView *)view;
//    NSString *qtype =[dataDict objectForKey:@"qtype"];
//    //更新收藏按钮
//    NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
//    BOOL isCollection = NO;
//    if ([favourite_flag isEqualToString:@"1"]) {
//        isCollection = YES;
//    }
//    [collectionBtn setSelected:isCollection];
//    //试题
//    if ([qtype isEqualToString:@"1"]||[qtype isEqualToString:@"2"]||[qtype isEqualToString:@"3"]) {
//        FMSCHBLog(@"self.paperArray:%d",[self.paperArray count]);
//        [dataDict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:[dataDict objectForKey:@"content"] forKey:@"questionContent"]];
//        NSString *option_a = [dataDict objectForKey:@"option_a"];
//        NSString *option_b = [dataDict objectForKey:@"option_b"];
//        NSString *option_c = [dataDict objectForKey:@"option_c"];
//        NSString *option_d = [dataDict objectForKey:@"option_d"];
//        NSString *option_e = [dataDict objectForKey:@"option_e"];
//        NSString *option_f = [dataDict objectForKey:@"option_f"];
//        
//        NSMutableArray *array_option = [NSMutableArray arrayWithCapacity:1];
//        if (option_a!=nil&&![option_a isEqualToString:@"(null)"]) {
//            [array_option addObject:option_a];
//        }
//        if (option_b!=nil&&![option_b isEqualToString:@"(null)"]) {
//            [array_option addObject:option_b];
//        }
//        if (option_c!=nil&&![option_c isEqualToString:@"(null)"]) {
//            [array_option addObject:option_c];
//        }
//        if (option_d!=nil&&![option_d isEqualToString:@"(null)"]) {
//            [array_option addObject:option_d];
//        }
//        if (option_e!=nil&&![option_e isEqualToString:@"(null)"]) {
//            [array_option addObject:option_e];
//        }
//        if (option_f!=nil&&![option_f isEqualToString:@"(null)"]) {
//            [array_option addObject:option_f];
//        }
//        [dataDict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:array_option forKey:@"options"]];
//        NSString *qtype = [dataDict objectForKey:@"qtype"];
//        BOOL isSingle = YES;
//        if ([qtype isEqualToString:@"1"]||[qtype isEqualToString:@"3"]) {
//            isSingle = YES;
//        }else if([qtype isEqualToString:@"2"]){
//            isSingle = NO;
//        }else{
//            
//        }
//        listView = [[PaperListView alloc] initWithFrame:CGRectMake(0, 0, FMSCREENWIDTH, swipeView.frame.size.height)isSingle:isSingle isShowAnswer:YES anlysise:NO dataDict:dataDict];
//        [listView setPaperDelegate:self];
//        listView.paperDict = [self.paperArray objectAtIndex:index];
//        [listView setBackgroundColor:[UIColor clearColor]];
//        [listView setTag:100];
//        return listView;
//    }else{
//        NSMutableDictionary *anlysisDict =[self.paperArray objectAtIndex:currentPage];
//        CaseQuestionView  *caseView = [[CaseQuestionView alloc] initWithFrame:CGRectMake(0, 0, FMSCREENWIDTH, swipeView.frame.size.height) isSingle:NO isShowAnswer:YES anlysise:NO dataDict:anlysisDict];
//        [caseView setBackgroundColor:[UIColor clearColor]];
//        return caseView;
//    }
//    return nil;
//}
- (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(HBListTableView *)view
{
    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:index];
//    if (view) {
//        view.tableType = _tableType;
//        [view setModelViewData:dataDict];
//        return view;
//    }
    HBListTableView *tableView = [[HBListTableView alloc] initWithFrame:CGRectMake(0, 0, FMSCREENWIDTH, swipeView.frame.size.height) style:UITableViewStyleGrouped];
    tableView.tableType = _tableType;
    [tableView setModelViewData:dataDict WithQuestionCount:self.paperArray.count];
    return tableView;
}
- (void)swipeViewCurrentItemIndexDidChange:(SwipeView *)swipeView
{
    currentPage =swipeView.currentItemIndex;
    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:currentPage];
    NSString *paper_title = [dataDict objectForKey:@"paper_title"];
    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%02li/%02lu题",paper_title,(unsigned long)(currentPage+1),(unsigned long)[self.paperArray count]];
    [titleLabel setText:paperTitleAndCount];
    
    NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
    BOOL isCollection = NO;
    if ([favourite_flag isEqualToString:@"1"]) {
        isCollection = YES;
    }
    [collectionBtn setSelected:isCollection];
    
    //update page control page
    if (swipeView.currentItemIndex==0&&currentPage==swipeView.currentItemIndex) {
        [ApplicationUtils makeToast:@"已第一页" withImageName:@"no" withView:self.view];
        return;
    }
    if ([self.paperArray count]-1 == swipeView.currentItemIndex) {
        [ApplicationUtils makeToast:@"已最后一页" withImageName:@"no" withView:self.view];
        return;
    }
}
-(void)swipeViewWillBeginDragging:(SwipeView *)swipeView{
    
}
- (void)swipeViewDidScroll:(SwipeView *)swipeView{
    
}

//- (void)swipeView:(SwipeView *)swipeView didSelectItemAtIndex:(NSInteger)index
//{
//    FMSCHBLog(@"Selected item at index %li", (long)index);
//}
@end
